package com.server.llh.llhserverwork.version;

import android.app.DownloadManager;
import android.app.DownloadManager.Request;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.net.Uri;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;
import android.webkit.MimeTypeMap;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

public class ApkDownLoad {
	
    public static final String DOWNLOAD_FOLDER_NAME = "lelaohui";
    public static final String DOWNLOAD_FILE_NAME   = "LLHNms.apk";
    public static final String APK_DOWNLOAD_ID = "apkDownloadId";
    
	public static String getDownloadFolderName() {
		return DOWNLOAD_FOLDER_NAME;
	}

	public static String getDownloadFileName() {
		return DOWNLOAD_FILE_NAME;
	}

	public static String getApkDownloadId() {
		return APK_DOWNLOAD_ID;
	}

	private Context context;
	private String url;
	private String notificationTitle;
	private String notificationDescription;
	
    private DownloadManager downloadManager;
    private CompleteReceiver completeReceiver;
    
	/**
	 * @param context 
	 * @param url 下载apk的url
	 * @param notificationTitle 通知栏标�?	 * @param notificationDescription 通知栏描�?	 */
    public ApkDownLoad(Context context, String url, String notificationTitle,
			String notificationDescription) {
		super();
		this.context = context;
		this.url = url;
		this.notificationTitle = notificationTitle;
		this.notificationDescription = notificationDescription;
		
		downloadManager = (DownloadManager)context.getSystemService(Context.DOWNLOAD_SERVICE);
		completeReceiver = new CompleteReceiver();
		
        /** register download success broadcast **/
        context.registerReceiver(completeReceiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
	}

	public void execute() {
		
		//清除已下载的内容重新下载
		long downloadId = PreferencesUtils.getLong(context, APK_DOWNLOAD_ID);
		System.out.println("downloadId=="+downloadId);
		if(downloadId != -1){
			downloadManager.remove(downloadId); 
			PreferencesUtils.removeSharedPreferenceByKey(context, APK_DOWNLOAD_ID);
		}
		System.out.println("ApkDownLoad   url=="+url);
		readFileSize(url);
		Request request = new Request(Uri.parse(url));
		
		System.out.println("request=="+request.toString());
		//设置Notification中显示的文字
        request.setTitle(notificationTitle);
        request.setDescription(notificationDescription);
		//设置可用的网络类�?		request.setAllowedNetworkTypes(Request.NETWORK_MOBILE  | Request.NETWORK_WIFI); 
		//设置状�?栏中显示Notification
		request.setNotificationVisibility(Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
        //不显示下载界�? 
		request.setVisibleInDownloadsUi(false); 
		//设置下载后文件存放的位置
        File folder = Environment.getExternalStoragePublicDirectory(DOWNLOAD_FOLDER_NAME);
        if (!folder.exists() || !folder.isDirectory()) {
            folder.mkdirs();
        }
        System.out.println("DOWNLOAD_FOLDER_NAME==="+Environment.getExternalStoragePublicDirectory(DOWNLOAD_FOLDER_NAME));
        request.setDestinationInExternalPublicDir(DOWNLOAD_FOLDER_NAME, DOWNLOAD_FILE_NAME);
        //设置文件类型  
        MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();  
        String mimeString = mimeTypeMap.getMimeTypeFromExtension(MimeTypeMap.getFileExtensionFromUrl(url));  
        request.setMimeType(mimeString); 
        //保存返回唯一的downloadId
        PreferencesUtils.putLong(context, APK_DOWNLOAD_ID, downloadManager.enqueue(request));
	}
	 private void readFileSize(String filePath) {
		 System.out.println("filePath"+filePath);
		 int size;
	     try {
	    	 if (!TextUtils.isEmpty(filePath)) {
	    		 InputStream f1 = new FileInputStream(filePath);
	    		 size = f1.available();
	    		 System.out.println("Total Available Bytes: " + size);
	    		 f1.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	class CompleteReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            /**
             * get the id of download which have download success, if the id is my id and it's status is successful,
             * then install it
             **/
            long completeDownloadId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, 0);
            long downloadId = PreferencesUtils.getLong(context, APK_DOWNLOAD_ID);
            System.out.println("completeDownloadId=="+completeDownloadId+",downloadId=="+downloadId);
            if (completeDownloadId == downloadId) {
            	
                // if download successful
                if (queryDownloadStatus(downloadManager, downloadId) == DownloadManager.STATUS_SUCCESSFUL) {
                	System.out.println("下载成功......");
                	//clear downloadId
                	PreferencesUtils.removeSharedPreferenceByKey(context, APK_DOWNLOAD_ID);
                	
                	//unregisterReceiver
                	context.unregisterReceiver(completeReceiver);
                	
                	//install apk
                    String apkFilePath = new StringBuilder(Environment.getExternalStorageDirectory().getAbsolutePath())
                            .append(File.separator).append(DOWNLOAD_FOLDER_NAME).append(File.separator)
                            .append(DOWNLOAD_FILE_NAME).toString();
                    
                    System.out.println("DownLoad apk file path=="+apkFilePath);
                    install(context, apkFilePath);
                }
            }
        }
    };
    
    /** 查询下载状�? */
    public static int queryDownloadStatus(DownloadManager downloadManager, long downloadId){
    	 int result = -1;
    	 DownloadManager.Query query = new DownloadManager.Query().setFilterById(downloadId);
         Cursor c = null;
         try {
             c = downloadManager.query(query);
             if (c != null && c.moveToFirst()) {
                 result = c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS));
                 int reasonIdx = c.getColumnIndex(DownloadManager.COLUMN_REASON);    
                 int titleIdx = c.getColumnIndex(DownloadManager.COLUMN_TITLE);    
                 int fileSizeIdx =     
                   c.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES);        
                 int bytesDLIdx =     
                   c.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR);    
                 String title = c.getString(titleIdx);    
                 int fileSize = c.getInt(fileSizeIdx);    
                 int bytesDL = c.getInt(bytesDLIdx);    
                   
                 // Translate the pause reason to friendly text.    
                 @SuppressWarnings("unused")
				int reason = c.getInt(reasonIdx);    
                 StringBuilder sb = new StringBuilder();    
                 sb.append(title).append("\n");   
                 sb.append("Downloaded ").append(bytesDL).append(" / " ).append(fileSize);    
               Log.d("下载大小===",sb.toString());    
             }
         } finally {
             if (c != null) {
                 c.close();
             }
         }
         return result;
    }
    
    /**
     * install app
     * 
     * @param context
     * @param filePath
     * @return whether apk exist
     */
    public static boolean install(Context context, String filePath) {
        Intent i = new Intent(Intent.ACTION_VIEW);
        File file = new File(filePath);
        if (file != null && file.length() > 0 && file.exists() && file.isFile()) {
            i.setDataAndType(Uri.parse("file://" + filePath), "application/vnd.android.package-archive");
            i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(i);
            return true;
        }
        return false;
    }
    
}
